package com.gxc.mq;

import com.gxc.enums.StatusEnum;
import com.gxc.dao.MqLogRepository;
import com.gxc.entity.MqLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消费.
 *
 * @author GongXincheng
 * @since 2019-08-27 15:16
 */
@Slf4j
@Component
public class ExceptionConsumerMq {

    private static Integer times = 0;

    @Resource
    private MqLogRepository mqLogRepository;

    @RabbitListener(queues = "${gxc.queue.exception}")
    public void handler(Integer id) {
        System.out.println("\n消费端接收消息次数：" + ++times);

        MqLog mqLog = mqLogRepository.findById(id).orElse(null);
        if (mqLog == null) {
            throw new RuntimeException("error in mq consumer #handler()：[MqLog] is null");
        }

        try {
            System.out.println("接收到消息：" + mqLog);

            int i = 1 / 0;

            // 更新mq日志状态
            mqLog.setStatus(StatusEnum.STATUS_YES.getCode());
            mqLogRepository.save(mqLog);
        } catch (Exception e) {
            mqLog.setStatus(StatusEnum.STATUS_EXP.getCode());
            mqLog.setErrorMsg(e.getMessage());
            mqLogRepository.save(mqLog);
            log.error("消费者出现异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

}
